/*
 * Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
 */
package com.xzkingdee.demo.baidu;

import com.xzkingdee.demo.baidu.util.Base64Util;
import com.xzkingdee.demo.baidu.util.FileUtil;
import com.xzkingdee.demo.baidu.util.GsonUtils;
import com.xzkingdee.demo.baidu.util.HttpUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AIP图像组合API
 */
public class ImgCensor {

    private static final String imgCensorUrl = "https://aip.baidubce.com/api/v1/solution/direct/img_censor";

    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
    public static String getResult(String filePath, String accessToken) {

//        String filePath = "C:/Users/Administrator/Desktop/21周年桌面/4.png";
        try {
            //请求参数
            Map<String, Object> sceneConf = new HashMap<String, Object>();
            Map<String, Object> ocrConf = new HashMap<String, Object>();
            ocrConf.put("recognize_granularity", "big");
            ocrConf.put("language_type", "CHN_ENG");
            ocrConf.put("detect_direction", true);
            ocrConf.put("detect_language", true);
            sceneConf.put("ocr", ocrConf);

            Map<String, Object> input = new HashMap<>();
            List<Object> scenes = new ArrayList<>();
            scenes.add("ocr");
            scenes.add("face");
            scenes.add("public");
            scenes.add("politician");
            scenes.add("antiporn");
            scenes.add("terror");
            scenes.add("webimage");
            scenes.add("disgust");
            scenes.add("watermark");

            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
//            String imageUrl = "http://aip.bdstatic.com/portal/dist/1522402512491/ai_images/technology/imagecensoring/demo-card-4.jpg";
//            input.put("imgUrl", imageUrl);//与image二者选一
            input.put("image", imgStr);//与image二者选一
            input.put("scenes", scenes);
            input.put("sceneConf", sceneConf);

            String params = GsonUtils.toJson(input);
            /**
             * 线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
             */
            return HttpUtil.post(imgCensorUrl, accessToken, "application/json", params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

}
